<?php

class ServiceController extends Controller {

    private $_form;
    public $layout = "columns2";

    public function accessRules() {
        return array(
            array('allow', 'actions' => array('create', 'helped', 'up', 'close'),'users' => array("@")),
            array('allow','actions' => array("list", 'view', 'rss','ajaxList'),'users' => array("*")),
            array( 'allow', 'actions' => array('delete'),  'expression' => 'Y::user()->isModerator()'),
            array('deny', 'users' => array('*'))
        );
    }

    /**
     * Получение списка просьб по ajax
     */
    public function actionAjaxList() {
        $criteria = new CDbCriteria(array(
            'limit'=>3, 'condition'=>'status = 0', 'order'=>'t_update DESC'
        ));
        $services = Service::search($criteria, true, true);
        $this->renderPartial('listAjax', compact("services"));
    }

    /**
     * Закрыть просьбу
     */
    public function actionClose() {
        $user = User::model()->findByPk(Y::userId());
        $service = Service::model()->findByPk($_GET['id']);

        if($service && $user && $service->owner_id != $user->id) {
            Y::flashRedir('errorMessage', 'Эта просьба Вам не принадлежит', "service/view", array("id" => $service->id));
        } else {
            $service->status = 1;
            $service->save();
            Y::flashRedir('success-block', 'Ваша просьба была закрыта', "service/view", array("id" => $service->id));
        }
    }

    /**
     * Поднять просьбу (может либо владелец либо модератор/администратор)
     */
    public function actionUp() {
        $user = User::model()->findByPk(Y::userId());
        $service = $this->loadService($_GET['id']);

        if(!$user){
            throw new CHttpException('403');
        }

        if($service->owner_id != $user->id && !Y::user()->isModerator()) {
            Y::flashRedir('errorMessage', 'Эта просьба Вам не принадлежит', "service/view", array("id" => $service->id));
        }

        if($user->rating >= Y::param('costUp') || Y::user()->isModerator()) {
            $service->up();
            if(!Y::user()->isModerator()) {
                $user->downRating(Y::param('costUp'));
            }
            Y::flashRedir('success-block', 'Ваша просьба была поднята', "service/view", array("id" => $service->id));
        } else {
            Y::flashRedir('errorMessage', 'У Вас не хватает рейтинга.', "service/view", array("id" => $service->id));
        }
    }

    /**
     * Выбираем того кто помог
     */
    public function actionHelped() {
        $service = $this->loadService($_GET['id']);

        if(isset($_GET['comment_id']) && Y::userId() == $service->owner_id) {
            $comment = Comment::model()->findByPk($_GET['comment_id']);

            if($comment) {
                $service->addHelper($comment->id);

                User::addHelped($comment->owner_id);
                User::addHelpedUs($service->owner_id);

                Y::flash('success-block', 'Вы отметили человека, который вам помог');
            }
        }

        $this->redirect("/service/" . $service->id . "#comment" . $_GET['comment_id']);
    }

    /**
     * Удаляем просьбу (модератор/администратор)
     */
    public function actionDelete() {
        $service = $this->loadService($_GET['id']);
        $service->delete();
        Y::flash("success-block", "Просьба успешно удалена.");
        $this->redirect("/service/list");
    }

    /**
     * Создание просьбы
     */
    public function actionCreate() {
        $this->breadcrumbs = array(
            "name" => '<a href="' . Y::url("service/list") . '">Список просьб</a>',
            "name2" => 'Создания просьбы'
        );

        $FormNewService = new FormNewService();
        $form = new CForm($FormNewService->config, $FormNewService);
        if($form->submitted('send') && $form->validate()) {
            $service_id = $FormNewService->createNew();
            Y::flashRedir('success-block','Ваша просьба успешно создана',"/service/{$service_id}");
        }

        $count = Service::isNewCreate(Yii::app()->user->id);
        $this->pageTitle = "Создание просьбы невозможно";
        $this->keyWord = "Сервис, просьбы, создать";
        $this->description = "Создать просьбу это просто, заполните форму помощи и ждите ответа";

        if($count > 0) {
            $this->render('create_fail', array('count' => $count));
        } else {
            $this->render('create', array('form' => $form));
        }
    }

    /**
     * Список просьб
     */
    public function actionList() {

        $criteria = new CDbCriteria();
        $criteria->with = array('owner', 'cont_comments', 'tags');

        if(isset($_GET['search'])) {
            $criteria->addSearchCondition('title', $_GET['search'], true, "OR");
            $criteria->addSearchCondition('text', $_GET['search'], true, "OR");
        }

        if(isset($_GET['filter'])) {
            $tag = Tags::model()->find("name = ?", array($_GET['filter']));

            if($tag){
                $tagsService = TagsService::model()->findAll("tag_id = ?", array($tag->id));
                $services_ids = array();
                foreach($tagsService as $tagService) {
                    $services_ids[] = $tagService->item_id;
                }
                if(!empty($services_ids))
                    $criteria->addInCondition('t.id', $services_ids);
            }
        }

        if(isset($_GET['userFilter'])) {
            $filter = UserFilter::model()->findByPk($_GET['userFilter']);

            if($filter && $filter->owner_id == Y::userId()) {
                $c = new CDbCriteria();
                $c->addInCondition('tag_id', explode(",", $filter->tag_ids));
                $tagsService = TagsService::model()->findAll($c);
                $services_ids = array();
                foreach($tagsService as $tagService) {
                    $services_ids[] = $tagService->item_id;
                }
                $criteria->addInCondition('t.id', $services_ids);
            }
        }

        $this->breadcrumbs = array("name" => "Список просьб");

        $services = Service::search($criteria, true, true);

        $this->pageTitle = "Список просьб";
        $this->keyWord = "Сервис, просьбы, список";
        $this->description = "Вы можете помочь чеорвеку? Так сделайте же это!";

        $this->render('list', compact("services"));
    }

    /**
     * Просмотр
     */
    public function actionView() {

        $service = $this->loadModel();
        $service->incView();

        $this->keyWord = YText::getKeyword($service->text);
        $this->description = YText::getDescription($service->text, 255, '');
        $this->pageTitle = $service->title;
        $this->breadcrumbs = array(
            "name" => CHtml::link("Список просьб", "/service/list"),
            "name2" => $service->title
        );

        $comment = Y::isAuthed() ? $this->newComment($service) : null;

        $item_services = $service->findSimilarService(Y::param('limitSimilar'));
        $item_suggests = $service->findSimilarSuggest(Y::param('limitSimilar'));

        $this->render('view', compact('service', 'comment', 'item_services', 'item_suggests'));
    }

    /**
     * Загрузить просьбу
     */
    public function loadModel() {
        if($this->_form === null) {
            if(isset($_GET['id'])) {
                $this->_form = Service::model()->with(array(
                      'comments.owner',
                      'rt' => array(
                          'condition' => 'rt.user_id = ' . Y::userId() . ' AND rt.type=' . Rating::TYPE_SERVICE
                      ),
                      'comments.rt')
                )->findByPk($_GET['id']);
            }
            if($this->_form === null) throw new CHttpException(404);
        }
        return $this->_form;
    }

    /**
     * Новый комментарий
     * @param $service
     * @return Comment
     */
    protected function newComment($service) {
        $comment = new Comment();
        $comment->type = Comment::TYPE_SERVICE;
        $comment->post_id = $service->id;
        if(isset($_POST['ajax']) && $_POST['ajax'] === 'comment-form') {
            echo CActiveForm::validate($comment);
            Yii::app()->end();
        }
        if(isset($_POST['Comment'])) {
            $comment->attributes = $_POST['Comment'];
            $comment->save();
            $service->t_lastcomment = time();
            $service->save();
            if($service->send_email == 1 && (time() - $service->last_send_email) > 24 * 60 * 60) {
                $this->sendMailNewComment($service);
                $service->last_send_email = time();
                $service->save();
            }
            $this->refresh();
        }
        return $comment;
    }

    /**
     * Пись-пись-пось-мо
     */
    protected function sendMailNewComment($service) {
        $user = User::model()->findByPk($service->owner_id);
        if(!$user->isOnline()) {
            $this->sendMail($user->email, '../email/new_comment_service', array('model' => $user, "post" => $service), 'Ответ в теме "' . $service->title . '"');
        }
    }

    /**
     * rss - агригатор
     */
    public function actionRss() {
        Yii::import('ext.feed.*');
        $feed = new EFeed();
        $feed->title = 'Просьбы';
        $feed->link = Y::baseUrl(true);
        $feed->description = 'Список просьб';
        $feed->setImage('hyho.by', 'http://hyho.by', 'http://trendclub.ru/upload/media/images/mik89/rss.jpg');
        $feed->addChannelTag('language', 'ru');
        $feed->addChannelTag('pubDate', date(DATE_RSS, time()));
        $criteria = new CDbCriteria();
        $criteria->limit = Y::param('countRss');
        $criteria->order = "t.t_create desc";
        $criteria->with = "owner";
        $serviecs = Service::model()->findAll($criteria);
        foreach($serviecs as $serviec) {
            $item = $feed->createNewItem();
            $item->title = $serviec->title;
            $item->link = Y::baseUrl(true) . "/service/" . $serviec->id;
            $item->date = $serviec->t_create;
            $item->description = strip_tags(YText::characterLimiter($serviec->text, 500));
            $item->addTag('author', $serviec->owner->username);
            $item->addTag('guid', Y::baseUrl(true) . "/service/" . $serviec->id, array('isPermaLink' => 'true'));
            $feed->addItem($item);
        }
        $feed->generateFeed();
    }
}
